/*
 * Copyright (c) 2016. 恒昌互联网运营中心.
 */

package com.credithc.eagleeye.redis;
import com.alibaba.fastjson.JSON;
import com.credithc.eagleeye.monitor.EagleMonitorMgr;
import com.credithc.eagleeye.vo.RpcTraceInfoVo;
import com.credithc.framework.redis.util.RedisSingleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
/**
 *
 * <br>类 名: EagleRedisQueueTask
 * <br>描 述: 从redis list提取日志
 * <br>版 本：v1.0.0
 * <br>
 * <br>历 史: (版本) 作者 时间 注释
 */
public class EagleRedisQueueTask implements Runnable {

	private final Logger logger = LoggerFactory.getLogger(EagleRedisQueueTask.class);
	private final static String EAGLE_EYE_REDIS_LIST_KEY = "eagle_eye_info_list";
	/**
	 * 从redis获取数据后，如果放入本地内存队列失败，暂停秒数后重试
	 */
	private final static int QUEUE_OFFER_EXCEPTION_SLEEP_SECONDS=3;

	private RedisSingleUtil redisSingleUtil;
	/**
	 * @param redisSingleUtil
	 */
    public EagleRedisQueueTask(RedisSingleUtil redisSingleUtil) {
		this.redisSingleUtil = redisSingleUtil;
    }

	@Override
	public void run() {
		while (true) {
			try {
				logger.debug("开始获取redis中EagleEye数据.....");
				String json = redisSingleUtil.listPop(EAGLE_EYE_REDIS_LIST_KEY);
				if(json!=null) {
					RpcTraceInfoVo rpcTraceInfoVo = JSON.parseObject(json, RpcTraceInfoVo.class);
					boolean success = EagleMonitorMgr.getInstance().offer(rpcTraceInfoVo);
					while (!success) {
						TimeUnit.SECONDS.sleep(QUEUE_OFFER_EXCEPTION_SLEEP_SECONDS);
						success = EagleMonitorMgr.getInstance().offer(rpcTraceInfoVo);
					}
				}else{
					Thread.sleep(500);
				}
			} catch (Exception e) {
				logger.error(String.format("获取redis中EagleEye数据 ERROR : %s", e.getMessage()));
				e.printStackTrace();
			}

		}
	}

}
